<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <div v-show="flag === 0">
                <el-form label-width="80px" :inline="true" size="small">
                    <el-form-item label="">
                        <el-input v-model="search"></el-input>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" size="small" icon="el-icon-search" @click="">查询</el-button>
                        <el-button type="default" size="small" @click="">清空</el-button>
                    </el-form-item>
                </el-form>
                <el-button type="primary" size="small" @click="addBtn" v-if="$hideBtn('btn.Role.add')">添加</el-button>
                <el-button type="danger" v-if="$hideBtn('btn.Role.remove')" size="small" :disabled="!selectList.length"
                    @click="">批量删除</el-button>
                <el-table :data="rolesList" border stripe style="margin:20px 0">
                    <el-table-column type="selection" align="center">
                    </el-table-column>
                    <el-table-column label="序号" type="index" align="center" width="100px">
                    </el-table-column>
                    <el-table-column label="角色名称" >
                        <template v-slot="{row,$index}">
                            <div v-if="row.flag">
                                <el-input ref="inputRef" v-model="row.newName"   size="mini" clearable ></el-input>
                                <el-button type="warning" size="mini" @click="row.flag=false">取消</el-button>
                                
                            </div>
                            <div v-else>{{row.roleName}}</div>
                            
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="300px">
                        <template v-slot="{ row, $index }">
                            <el-button type="info" size="mini" icon="el-icon-user-solid" @click="setRolePower(row)">
                            </el-button>
                            <el-button type="primary" size="mini" icon="el-icon-check" @click="updateBtn(row)"></el-button>
                            <el-button type="warning" size="mini" icon="el-icon-edit-outline" @click="editBtn(row)"></el-button>
                            <el-button type="danger" size="mini" icon="el-icon-delete" @click=""></el-button>

                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination @size-change="sizeChange" @current-change="getRoleList" :current-page.sync="currentPage"
                    :page-sizes="[3, 5, 7, 9]" :page-size="pageSize" layout=" prev, pager, next, jumper,->,sizes,total"
                    :total="total" :pager-count="7">
                </el-pagination>
                <!-- 新增角色对话框 -->
                <el-dialog title="添加角色" :visible.sync="dialogFormVisible" width="30%" style="height:400px">
                    <el-form :model="form" :rules="rules" ref="formRef">
                        <el-form-item label="请输入新名称：" label-position="top" prop="roleName">
                            <el-input v-model="form.roleName" size="small" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
                        <el-button type="primary" @click="save" size="small">确 定</el-button>
                    </div>
                </el-dialog>
            </div>
            <div v-show="flag === 1">
                <el-input v-model="roleName" disabled size="small" clearable style="margin:20px 0"></el-input>

                <el-tree :data="rolePermissionList" show-checkbox node-key="id" default-expand-all
                    :default-checked-keys="checkedKeys" :props="defaultProps" ref="treeRef">
                </el-tree>
                <div style="margin:20px 0">
                    <el-button type="primary" size="small" @click="saveTree">保存</el-button>
                    <el-button size="small" @click="flag=0">取消</el-button>
                </div>
            </div>


        </el-card>

    </div>
</template>

<script>
import { nextTick } from 'process';

export default {
    data: () => {
        return {
            flag: 0,
            search: "",
            selectList: [],
            currentPage: 1,
            pageSize: 3,
            rolesList: [],
            total: 0,
            dialogFormVisible: false,
            form: {
                roleName: ""
            },
            rules: {
                roleName: [
                    { required: true, message: "角色名不能为空！", trigger: "blur" },
                    { min: 2, message: "角色名不能少于两个字符", trigger: "change" }
                ]
            },
            rolePermissionList: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            checkedKeys: [],
            roleName: "",
            roleId: ""




        }
    },
    computed: {},
    methods: {
        async getRoleList() {
            let result = await this.$API.roles.getRoleListRes(this.currentPage, this.pageSize);
            this.rolesList = result.data.items;
            this.total = result.data.total;
        },
        sizeChange(pageSize) {
            this.pageSize = pageSize;
            this.currentPage = 1;
            this.getRoleList();
        },
        // 添加角色
        addBtn() {
            this.dialogFormVisible = true;
        },
        // 添加的保存按钮
        save() {
            this.$refs.formRef.validate(async (success) => {
                if (success) {
                    try {
                        await this.$API.roles.addRoleRes(this.form);
                        this.currentPage = 1;
                        this.getRoleList();
                        this.dialogFormVisible = false;
                        this.$message.success("添加成功");
                    } catch (error) {
                        this.$message.error("添加失败");
                    }
                }
            })


        },
        // 筛选树形结构中默认选中的节点id
        getCheckKey(arr) {

            return arr.forEach(item => {
                if (item.children && item.children.length) {

                    this.getCheckKey(item.children);
                }
                if (item.select) {
                    if (item.children && item.children.length) {

                        let flag = item.children.every(item => item.select);
                        if (flag) {
                            this.checkedKeys.push(item.id);
                        }
                    }

                }


            });


        },

        // 设置角色权限
        async setRolePower(row) {
            this.flag = 1;
            nextTick(() => {
                this.rolePermissionList = [];
                this.checkedKeys = [];
            })
            let result = await this.$API.roles.getRolePermissionRes(row.id);
            this.rolePermissionList = result.data.children;
            this.getCheckKey(result.data.children);
            this.roleName = row.roleName;
            this.roleId = row.id;

            console.log("选中的", this.checkedKeys);
        },
        // 保存树形选择
        async saveTree() {
            let arr1 = this.$refs.treeRef.getCheckedKeys(false);
            let arr2 = this.$refs.treeRef.getHalfCheckedKeys();
            let allArr = arr1.concat(arr2);
            let permissionId = allArr.join(",");
            try {
                await this.$API.roles.setRolePermissionRes(this.roleId, permissionId);
                this.flag = 0;

                this.getRoleList();
                this.$message.success("设置成功")

            } catch (error) {
                this.$message.error("设置失败")
            }

        },
        //编辑按钮 
        editBtn(row){
            this.$set(row,"flag",true);
            this.$set(row,"newName",row.roleName);
            console.log(row);
        },
        // 更新
        async updateBtn(row){
            let data = row;
            if(row.newName){
                data.roleName = data.newName;
            }           
            try {
                await this.$API.roles.updateRes(data);
                this.$message.success("更新成功");
                this.getRoleList();
            } catch (error) {
                this.$message.error("更新失败")
            }

        }
    },
    watch:{
        rolesList:{
            handler(val){
                console.log(val);
                // this.rolesList = val;
            },
            deep:true
        }
    },
    mounted() {
        this.getRoleList();
    },
}
</script>

<style lang="scss" scoped>

</style>